/**
 * 时间处理
 * 
 */
let app = getApp(); //获取应用实例
const formatTime = time => {
    let date = new Date(time)
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return `${hour}:${minute}:${second}`
}
/**
 * 生成富文本节点
 */
function generateRichTextNode(text) {
    let tempStr = text
    let richTextNode = []
    let leftBracketIndex = tempStr.indexOf('[')
    let rightBracketIndex = tempStr.indexOf(']')
    let countOfWord = 0
    Array.from(tempStr).map(item => {
        if (item != '[' && item != ']') {
            countOfWord++
        }
    })
    if (leftBracketIndex == -1 || rightBracketIndex == -1 || countOfWord == 0) { //没有emoji
        richTextNode.push({
            type: 'text',
            text: tempStr
        })
        return richTextNode
    }
    while (tempStr.length != 0) {
        leftBracketIndex = tempStr.indexOf('[')
        rightBracketIndex = tempStr.indexOf(']')
        if (leftBracketIndex == 0) { // 开头是[
            rightBracketIndex = tempStr.indexOf(']')
            if (rightBracketIndex == -1) {
                richTextNode.push({
                    type: 'text',
                    text: tempStr
                })
                tempStr = ''
            } else {
                let emojiName = tempStr.slice(0, rightBracketIndex + 1)
                if (emoji[emojiName]) { // 有效emoji
                    richTextNode.push({
                        name: 'img',
                        attrs: {
                            width: '30rpx',
                            height: '30rpx',
                            src: emoji[emojiName].img
                        }
                    })
                } else { //无效emoji
                    richTextNode.push({
                        type: 'text',
                        text: emojiName
                    })
                }
                tempStr = tempStr.substring(rightBracketIndex + 1, tempStr.length)
            }
        } else { // 开头不是[
            if (leftBracketIndex == -1) { // 最后全是文字
                richTextNode.push({
                    type: 'text',
                    text: tempStr.slice(0, tempStr.length)
                })
                tempStr = ''
            } else {
                richTextNode.push({
                    type: 'text',
                    text: tempStr.slice(0, leftBracketIndex)
                })
                tempStr = tempStr.substring(leftBracketIndex, tempStr.length + 1)
            }
        }
    }
    return richTextNode
}
/**
 * 封装post
 */
function ajaxPost(url, data, success, fail, ) {
    if (!data.token) {
        data.token = wx.getStorageSync('token')
    }
    wx.request({
        url: app.globalData.ajaxUrl + url + '?t=' + Date.parse(new Date()),
        header: {
            'content-type': 'application/x-www-form-urlencoded',
        },
        method: 'POST',
        data: data,
        success: function (res) {
            console.group(url)
            console.log('%c 请求路径--->', 'color: #1ba01b', url)
            console.log('%c 请求参数--->', 'color: #1ba01b', data)
            console.log('%c 成功--->', 'color: #1ba01b', res.data)
            console.groupEnd()
            success(res.data);
        },
        fail: function (res) {
            console.group(url)
            console.error('%c 请求路径--->', 'color: #1ba01b', url)
            console.error('%c 请求参数--->', 'color: #1ba01b', data)
            console.error('%c 失败--->', 'color: #d66850', res)
            console.groupEnd()
            wx.showToast({
                title: '网络开了下小差，再试一次吧',
                icon: 'none',
                duration: 2000
            })
        },
    });

}
/**
 * 封装toast
 */
function showToast(type, text, obj) {
    let param = {
        duration: (obj && obj.duration) || 2000,
        mask: (obj && obj.isMask) || false
    }
    switch (type) {
        case 'text': {
            param['title'] = text || ''
            param['icon'] = 'none'
            break
        }
        case 'loading': {
            param['title'] = text || ''
            param['icon'] = 'loading'
            break
        }
        case 'success': {
            param['title'] = text || ''
            param['icon'] = 'success'
            break
        }
        case 'error': {
            param['title'] = text || ''
            param['image'] = '/images/error.png'
            break
        }
        default: {
            break
        }
    }
    wx.showToast(param)
}
/** 
 * 时间戳格式化函数 
 * @param  {string} date    格式 
 * @param  {int}    fmt 要格式化的时间 默认为当前时间 
 * @return {string}           格式化的时间字符串 
 */


function Time(time, fmt) {
    let date = new Date(time);
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
    }
    return fmt;
};

function padLeftZero(str) {
    return ('00' + str).substr(str.length);
};


module.exports = {
    Time,
    formatTime,
    generateRichTextNode,
    ajaxPost,
    showToast,
}